package team.xiaobaiya.gptchatrobot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import team.xiaobaiya.gptchatrobot.entity.chat.ConverseRequestBody;
import team.xiaobaiya.gptchatrobot.entity.chat.QuestionRequestBody;
import team.xiaobaiya.gptchatrobot.handler.chat.ConverseHandleWrapper;
import team.xiaobaiya.gptchatrobot.handler.chat.QuestionMessageListBuilder;
import team.xiaobaiya.gptchatrobot.rights.RightsManager;
import team.xiaobaiya.gptchatrobot.rights.UserKeyCheckResult;

/**
 * @ClassName ChatController
 * @Author Feng Yingnan
 * @Email fengyn1211@163.com
 * @Date 2023/4/6 17:00
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("chat")
public class ChatController {
    @Autowired
    RightsManager rightsManager;

    @PostMapping("/converse")
    public SseEmitter converseEvents(@RequestBody ConverseRequestBody requestBody) {
        log.info("{}", requestBody);
        // 封装对话处理
        ConverseHandleWrapper converseHandleWrapper =
                new ConverseHandleWrapper(requestBody.getUserKey(), requestBody.getMessageList());
        return converseHandleWrapper.handle();
    }

    @PostMapping("/question")
    public SseEmitter question(@RequestBody QuestionRequestBody requestBody) {
        ConverseHandleWrapper converseHandleWrapper = new ConverseHandleWrapper();
        // 参数检查
        if (!StringUtils.hasLength(requestBody.getQuestion())) {
            return converseHandleWrapper.sendErrorAndEnd("你的问题是空的");
        }
        // 鉴权
        UserKeyCheckResult userKeyCheckResult = rightsManager.userKeyCheck(requestBody.getUserKey());
        if (userKeyCheckResult.notOk()) {
            return converseHandleWrapper.sendErrorAndEnd(userKeyCheckResult.msg);
        }
        // 锁定user key
        rightsManager.lockUserKey(requestBody.getUserKey());
        // 创建上下文
        converseHandleWrapper.messageItemList(QuestionMessageListBuilder.build(requestBody.getQuestion()));
        // 对话
        return converseHandleWrapper.doConverse();
    }

}
